<template>
  <div class="user-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="handleAdd">添加用户</el-button>
        </div>
      </template>

      <el-skeleton v-if="loading" :rows="5" class="mb-4" />

      <el-table v-else :data="userList" style="width: 100%">        
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="created_at" label="创建时间" />
        <el-table-column prop="is_superuser" label="管理员">
          <template #default="{ row }">
            <el-tag
                :type="row.is_superuser === true? 'success' : 'info'">
              {{ row.is_superuser === true ? '是' : '不是' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ip" label="IP地址" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="primary" link @click="openAssignDialog(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-alert v-if="error" type="error" description="数据加载失败，请重试" show-icon class="mt-4" />
    </el-card>

    <!-- 添加用户弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加用户"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" placeholder="请输入密码" />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirm_password">
          <el-input v-model="formData.confirm_password" placeholder="请输入确认密码" />
        </el-form-item>

      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配微信号弹窗 -->
    <el-dialog
      v-model="assignDialogVisible"
      :title="`分配微信号给用户：${currentUser?.username || ''}`"
      width="1000px"
    >
      <div class="assign-container">
        <div class="column">
          <h4>该用户已绑定的微信号</h4>
          <el-table :data="userWxUsers" height="320" style="width:100%">
            <el-table-column prop="nickname" label="昵称" width="150"/>
            <el-table-column prop="device_id" label="device_id" min-width="150"/>
            <el-table-column label="操作" width="100">
              <template #default="{ row }">
                <el-button type="danger" link @click="handleUnassign(row)">移除绑定</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="column">
          <h4>所有微信号（除已绑定自己之外）</h4>
          <el-table :data="allWxUsers" height="320" style="width:100%" @selection-change="onSelectWxUsers">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="nickname" label="昵称" width="180"/>
            <el-table-column prop="device_id" label="device_id" min-width="150"/>
            <el-table-column prop="current_user" label="当前绑定的用户" width="120">
              <template #default="{ row }">
                <el-tag v-if="row.current_user" type="info" size="small">
                  {{ row.current_user }}
                </el-tag>
                <el-tag v-else type="warning" size="small">
                  未分配
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="assigning" @click="handleAssign">分配选中</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

// 更新用户接口定义
interface User {
  user_id?: string | number
  username: string
  created_at?: string
  is_superuser?: boolean
  ip?: string
}

interface WxUserBrief {
  device_id: string
  nickname: string
  user_id?: string | number | null
  current_user?: string | null
}

// 定义表单数据接口
interface UserFormData {
  username: string
  password: string
  confirm_password: string


}

const userList = ref<User[]>([])
const loading = ref(true)
const error = ref(false)

// 在 script setup 中添加必要的响应式变量
const dialogVisible = ref(false)
const formData = ref<UserFormData>({
  username: '',
  password: '',
  confirm_password: ''
})

// 分配弹窗相关
const assignDialogVisible = ref(false)
const currentUser = ref<User | null>(null)
const userWxUsers = ref<WxUserBrief[]>([])
const allWxUsers = ref<WxUserBrief[]>([])
const selectedWxUsers = ref<WxUserBrief[]>([])
const assigning = ref(false)

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirm_password: [
    { required: true, message: '请输入确认密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== formData.value.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const formRef = ref()

// 页面加载时获取数据
onMounted(async () => {
  try {
    loading.value = true
    const response = await axios.get('/users')
    userList.value = response.data.data.users
    error.value = false
  } catch (err) {
    console.error('获取用户数据失败:', err)
    error.value = true
  } finally {
    loading.value = false
  }
})

const handleAdd = () => {
  dialogVisible.value = true
}

const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid: boolean) => {
    if (valid) {
      const submitData = {
        username: formData.value.username,
        password: formData.value.password,
        confirm_password: formData.value.confirm_password,
      }

      axios.post('/register', submitData)
      .then(response => {
        ElMessage.success('添加用户成功')
        dialogVisible.value = false
        formRef.value.resetFields()
        
        // 添加成功后重新获取用户列表
        axios.get('/users')
        .then(res => {
          userList.value = res.data.data.users
        })
        .catch(err => {
          console.error('重新获取用户列表失败:', err)
        })
      })
      .catch(error => {
        ElMessage.error('添加用户失败：' + (error.response?.data?.msg || error.message))
      })
    }
  })
}
const getUsernameByUserId = (userId: string) => {
  if (!userId) return '';
  const user = userList.value.find(user => user.user_id === userId);
  return user ? user.username : '未知用户';
}
// 打开分配弹窗
const openAssignDialog = async (row: User) => {
  currentUser.value = row
  selectedWxUsers.value = []
  // 显示加载状态
  assigning.value = true
  try {
    // 先加载数据
    const [userWxResponse, allWxResponse] = await Promise.all([
      // 获取该用户已绑定的微信号
      axios.get(`/users/${row.user_id}/wx_users`),
      // 获取所有微信号
      axios.get('/wx_users')
    ])

    // 数据加载完成后再打开弹窗
    assignDialogVisible.value = true

    if (!userWxResponse.data.data) {
      ElMessage.warning('没有微信设备绑定记录')
      userWxUsers.value = []
      // return
    } else {
      // 处理该用户已绑定的微信号数据
      userWxUsers.value = (userWxResponse.data.data || userWxResponse.data || []).map((x: any) => ({ 
        device_id: x.device_id, 
        nickname: x.nickname, 
        user_id: x.user_id,
        current_user: getUsernameByUserId(x.user_id)
      }))
    }

    
    // 处理所有微信号数据（包含当前绑定用户信息）
    const currentUserWxIds = userWxUsers.value.map(wx => wx.device_id);
    allWxUsers.value = (allWxResponse.data.data || allWxResponse.data || []).filter((x: any) => !currentUserWxIds.includes(x.device_id))
        .map((x: any) => ({
      device_id: x.device_id, 
      nickname: x.nickname, 
      user_id: x.user_id,
      current_user: getUsernameByUserId(x.user_id)
    }))
  } catch (e: any) {
    ElMessage.error('加载微信号失败：' + (e.response?.data?.msg || e.message))
  } finally {
    // 关闭加载状态
    assigning.value = false
  }
}

const onSelectWxUsers = (rows: WxUserBrief[]) => {
  selectedWxUsers.value = rows
}

// 提交分配
const handleAssign = async () => {
  if (!currentUser.value || selectedWxUsers.value.length === 0) {
    ElMessage.warning('请选择要分配的微信号')
    return
  }
  assigning.value = true
  try {
    // 逐个调用后端接口分配
    await Promise.all(selectedWxUsers.value.map(item => {
      return axios.post('/wx_users/assign', {
        user_id: currentUser.value!.user_id,
        device_id: item.device_id
      })
    }))
    ElMessage.success('分配成功')
    // 重新拉取该用户的 wx_user 列表和所有 wx_users 列表
    const [userWxResponse, allWxResponse] = await Promise.all([
      axios.get(`/users/${currentUser.value.user_id}/wx_users`),
      axios.get('/wx_users')
    ])
    // 更新左侧表格（已分配的微信号）
    userWxUsers.value = (userWxResponse.data.data || userWxResponse.data || []).map((x: any) => ({ 
      device_id: x.device_id, 
      nickname: x.nickname, 
      user_id: x.user_id,
      current_user: x.current_user || x.username || null
    }))
    // 更新右侧表格（所有微信号，排除已分配给当前用户的）
    const currentUserWxIds = userWxUsers.value.map(wx => wx.device_id);
    allWxUsers.value = (allWxResponse.data.data || allWxResponse.data || [])
      .filter((x: any) => !currentUserWxIds.includes(x.device_id))
      .map((x: any) => ({
        device_id: x.device_id, 
        nickname: x.nickname, 
        user_id: x.user_id,
        current_user: getUsernameByUserId(x.user_id)
      }))
    selectedWxUsers.value = []
  } catch (e: any) {
    ElMessage.error('分配失败：' + (e.response?.data?.msg || e.message))
  } finally {
    assigning.value = false
  }
}

// 移除微信号绑定（将微信号分配给admin用户）
const handleUnassign = async (row: WxUserBrief) => {
  ElMessageBox.confirm(
    `确定要移除微信号 "${row.nickname}" 的绑定吗？移除后将默认分配给admin用户。`,
    '确认移除绑定',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
      // 首先查找admin用户ID
      const adminUser = userList.value.find(user => user.username === 'admin');
      if (!adminUser) {
        ElMessage.error('未找到admin用户')
        return
      }
      
      // 调用后端接口将微信号分配给admin用户
      await axios.post('/wx_users/assign', {
        user_id: adminUser.user_id,
        device_id: row.device_id
      })
      
      ElMessage.success('移除绑定成功')
      
      // 重新拉取该用户的 wx_user 列表
      if (currentUser.value) {
        const userWxResponse = await axios.get(`/users/${currentUser.value.user_id}/wx_users`)
        userWxUsers.value = (userWxResponse.data.data || userWxResponse.data || []).map((x: any) => ({ 
          device_id: x.device_id, 
          nickname: x.nickname, 
          user_id: x.user_id,
          current_user: x.current_user || x.username || null
        }))
      }
      
      // 重新拉取所有微信号列表
      const allWxResponse = await axios.get('/wx_users')
      // 过滤掉当前用户已经绑定的微信号
      const currentUserWxIds = userWxUsers.value.map(wx => wx.device_id);
      allWxUsers.value = (allWxResponse.data.data || allWxResponse.data || [])
        .filter((x: any) => !currentUserWxIds.includes(x.device_id))
        .map((x: any) => ({ 
          device_id: x.device_id, 
          nickname: x.nickname, 
          user_id: x.user_id,
          current_user: getUsernameByUserId(x.user_id)
        }))
    } catch (e: any) {
      ElMessage.error('移除绑定失败：' + (e.response?.data?.msg || e.message))
    }
  })
  .catch(() => {
    ElMessage.info('已取消移除绑定')
  })
}

const handleDelete = (row: User) => {
  ElMessageBox.confirm(
    `确定要删除用户 "${row.username}" 吗？此操作不可恢复。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    axios.delete(`/users/${row.user_id}`)
    .then(response => {
      ElMessage.success('删除用户成功')
      userList.value = userList.value.filter(x => x.user_id !== row.user_id)
    })
    .catch(error => {
      ElMessage.error('删除用户失败：' + (error.response?.data?.msg || error.message))
    })
  })
  .catch(() => {
    ElMessage.info('已取消删除')
  })
}
</script>

<style scoped lang="scss">
.user-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.assign-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 16px;
  width: 100%;
  box-sizing: border-box;
}

/* 确保表格容器不会溢出 */
.assign-container .column {
  overflow: hidden;
}

/* 优化表格列的宽度适应 */
.el-table .el-table__header-wrapper,
.el-table .el-table__body-wrapper {
  width: 100%;
  overflow-x: auto;
}

.assign-container .column h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}
</style>